import GameMgr from './GameManager'
import { getRandomFromAToB } from './utils/index'

export default class Monster extends cc.Component {
  // 怪物属性
  ATK: number = 10

  HP: number = 100

  ASPD: number = 1

  CRT: number = 0.1

  isDead: boolean = false

  waitQueue: Promise<any>[] = []

  async init() {
    await this.changeRole('monster1')
  }

  reset() {
    this.ATK = 10
    this.HP = 100
    this.ASPD = 1
    this.isDead = false
  }

  /**
   * 切换人物皮肤
   * GameMgr.instance.monsterAnimation.roleName = 'role01'
   * 切换人物动作
   * GameMgr.instance.monsterAnimation.play('attack')
   * @param url 路径
   */
  async changeRole(url: string) {
    this.waitQueue = [this.loadRole(url)]
    await Promise.all(this.waitQueue)
    GameMgr.instance.MonstersAlive = GameMgr.instance.MonstersAlive.sort((a, b) => a.node.position.x - b.node.position.x) //得到离英雄最近的怪物node排序
    this.waitQueue = []
  }

  loadRole(url: string) {
    return new Promise((resolve, reject) => {
      cc.resources.load(`prefab/monsters/${url}`, cc.Prefab, (err, prefab: cc.Prefab) => {
        if (!err) {
          const node = cc.instantiate(prefab)
          const x = getRandomFromAToB(300, 450)
          const y = getRandomFromAToB(150, 250)
          node.setPosition(x, y)
          GameMgr.instance.layoutTop.addChild(node)
          const animation = node.getComponent(cc.Animation)
          animation.play('run')
          animation.on(cc.Animation.EventType.FINISHED, () => this.onAnimationFinished(this, animation))
          GameMgr.instance.MonstersAlive.push({ node, target: this })
          resolve(true)
          return
        }
        console.error(err)
        reject(err)
      })
    })
  }

  onAnimationFinished(target, animation) {
    GameMgr.instance.roleInstance.getHurtHP(GameMgr.instance.roleNode)
    if (target.HP > 0) {
      setTimeout(() => {
        animation.play('attack')
      }, 1000)
    }
  }

  getHurtHP(node) {
    const progressBar = node.getComponentInChildren(cc.ProgressBar)
    progressBar.node.active = true
    const bar = progressBar.getComponentInChildren(cc.Sprite)
    const label = node.getComponentInChildren(cc.Label)
    const roleDamage = GameMgr.instance.roleInstance.ATK
    label.node.active = true
    label.string = roleDamage
    cc.tween(label.node)
      .to(0.3, { position: new cc.Vec2(0, 90), scale: 1.5 })
      .call(() => {
        label.node.active = false
        label.node.position = new cc.Vec2(0, 70)
      })
      .start()
    this.HP -= roleDamage
    bar.fillRange = this.HP / 100
    if (this.HP <= 0) {
      node.removeFromParent()
      GameMgr.instance.MonstersAlive.shift()
    }
  }
}
